package com.ldgk.pim.client.presenter;

import com.google.gwt.core.client.JsArray;
import com.google.gwt.search.client.LocalResult;
import com.ldgk.pim.client.util.GeoHash;
import com.ldgk.pim.client.view.MapView;
import com.ldgk.pim.client.view.MarkerView;
import com.ldgk.pim.client.view.components.PowerMarker;
import com.ldgk.pim.data.Place;

/**
 * Handlers marker gui events
 * @version 1.0
 *
 */
public class MarkerPresenter implements Presenter{
	/** Marker view */
	private MarkerView markerView;
	/** Map view */
	private MapView mapView;
	
	/**
	 * Default constructor
	 * @param markerView
	 * @param mapView
	 */
	public MarkerPresenter(MarkerView markerView, MapView mapView){
		this.markerView = markerView;
		this.markerView.setPresenter(this);
		this.mapView = mapView;
	}
	
	/**
	 * Create a map marker based on a distribution place
	 * @param dp - Distribution Place
	 * @return Power Marker
	 */
	public PowerMarker createMarker(Place dp){
		return this.markerView.buildDistributionPlaceMarker(dp);
	}

	/**
	 * Create a map marker based on a google local search result
	 * @param result - Google Local Search Result
	 * @return Power Marker
	 */
	public PowerMarker createMarker(LocalResult result){
		return this.markerView.buildLocalResultMarker(convertLocalResultToDistributionPlace(result));
	}
	
	/**
	 * Retrieves the presente's map view
	 * @return
	 */
	public MapView getMapView(){
		return this.mapView;
	}

	/**
	 * Converts google local search results in
	 * distribution places
	 * @param lr - local search result
	 * @return distribution place
	 */
	private Place convertLocalResultToDistributionPlace(LocalResult lr){
		Place dp = new Place();
		//Set name
		dp.setName(lr.getTitleNoFormatting());
		//Set address
		dp.setAddress(lr.getStreetAddress()+" - "+lr.getCity()+" - "+lr.getRegion());
		//Set phones
		StringBuilder tmp = new StringBuilder(200);
		if( lr.getPhoneNumbers() != null && lr.getPhoneNumbers().length() > 0){
			JsArray<LocalResult.PhoneNumber> tmpPhones = lr.getPhoneNumbers();
			int length = tmpPhones.length();
			for(int i=0; i<length; i++){
				tmp.append(tmpPhones.get(i).getNumber()).append("|");
			}
			dp.setPhones(tmp.length() > 0? tmp.toString() : "");
		}
		//Set lat/lng
		dp.setLat(lr.getLat());
		dp.setLng(lr.getLng());
		
		String geohash = GeoHash.fromLatLng(lr.getLat(),lr.getLng()).toBase32();
		dp.setGeoHash(geohash);
		
		return dp;
	}
}
